import { createRouter, createWebHistory } from 'vue-router'

import { useTokenStore } from '@/stores/token.js'
import useUserInfoStore from '@/stores/userInfo.js'

// 公共页面
import RegisterVue from '@/views/aute/Register.vue'
import LoginVue from '@/views/aute/Login.vue'

//布局页面
import UserLayoutVue from '@/layouts/UserLayout.vue'
import AdminLayoutVue from '@/layouts/AdminLayout.vue'

// 用户页面
import PostListVue from '@/views/post/list.vue'
import PostCreateVue from '@/views/post/Create.vue'
import PostDetailVue from '@/views/post/Detail.vue'
import PostWoekCreateVue from '@/views/post/WoekCreate.vue'
import PostWoekDetailVue from  '@/views/post/WoekDetail.vue'
//校园生活
import CarFriendsVue from '@/views/live/CarFriends.vue'
import LostFoundVue from '@/views/live/LostFound.vue'
import MarketVue from '@/views/live/Market.vue'
//校园机遇
import MassVue from '@/views/chance/Mass.vue'
import StudyVue from '@/views/chance/Study.vue'
import WoekVue from '@/views/chance/Woek.vue'
// 导入用户中心布局组件
import UserCenterLayoutVue from '@/layouts/UserCenterLayout.vue'
// 导入用户中心子页面
import UserProfilefoVue from '@/views/user/profile.vue'
import UserPostsVue from '@/views/user/Posts.vue'
import UserPostEditVue from '@/views/user/PostEdit.vue'
import UserLikesFavoritesVue from '@/views/user/LikesFavorites.vue'
import UserFollowVue from '@/views/user/Follow.vue'
import UserDetailVue  from '@/views/user/Detail.vue'
import UserSettingsVue from '@/views/user/Settings.vue'
import UserMessagesVue from '@/views/user/Messages.vue'
import HelpVue from '@/views/user/Help.vue'

// 管理员页面
import AdminDashboardVue from '@/views/admin/Dashboard.vue'
// 管理用户页面
import AdminUsersVue from '@/views/admin/Users.vue'
import AdminUserDetailVue from '@/views/admin/UserDetail.vue'
// 帖子列表页面组件
import AdminPostsVue from '@/views/admin/Posts.vue'
// 导入管理员帖子详情页面组件
import AdminPostsDetailVue from '@/views/admin/posts/Detail.vue'
import AdminPostsWoekDetailVue from '@/views/admin/posts/WoekDetail.vue'
//帖子版块、详细分类组件
import AdminPostsCategoriesVue from '@/views/admin/posts/Categories.vue'
import AdminPostsItemTypeVue from '@/views/admin/posts/ItemTypes.vue'
//帖子评论管理组件
import AdminPostsCommentsVue from '@/views/admin/posts/Comments.vue'


const routes = [
  // 公共路由（无需认证）
  { path: '/register', name: 'register', component: RegisterVue, meta: { requiresAuth: false } },
  { path: '/login', name: 'login', component: LoginVue,  meta: { requiresAuth: false } },
  // 用户路由（需要用户认证）
   {
    path: '/',
    component: UserLayoutVue, // 使用布局组件
    meta: { requiresAuth: true },
    children: [
      { path: '', name: '首页',component: PostListVue},
      { path: 'post/detail/:id', name: '帖子详情', component: PostDetailVue },
      { path: 'post/woekdetail/:id', name: '实习/兼职详情', component: PostWoekDetailVue, props: true },
      { path: 'post/create', name: '信息发布', component: PostCreateVue,},
      { path: 'post/woekcreate', name: '机遇发布', component: PostWoekCreateVue,},
      { path: 'messages', name: '消息', component: UserMessagesVue },
      { path: 'user/Detail/:id', name: '用户详情', component: UserDetailVue },
      //校园生活
      { path: 'live/CarFriends', name: '拼车交友', component: CarFriendsVue },
      { path: 'live/LostFound', name: '失物招领', component: LostFoundVue },
      { path: 'live/Market', name:'二手市场', component: MarketVue },
      //校园机遇
      { path: 'chance/Mass', name: '社团活动', component: MassVue },
      { path: 'chance/Study' , name: '学习交流', component: StudyVue },
      { path: 'chance/Woek' ,name: '实习兼职', component: WoekVue},
      //个人中心
      {
        path: 'user',
        component: UserCenterLayoutVue,
        children: [
          { path: 'profile', name: '个人信息', component: UserProfilefoVue },
          { path: 'posts', name: '我的发布', component: UserPostsVue },
          // 编辑的路径和参数格式
          { path: 'posts/edit/:id', name: '编辑帖子', component: UserPostEditVue },
          { path: 'LikesFavorites', name: '点赞收藏', component: UserLikesFavoritesVue },
          { path: 'follow', name: '关注与粉丝', component: UserFollowVue },
          { path: 'help', name: '帮助中心', component: HelpVue },
          { path: 'settings', name: '设置', component: UserSettingsVue }
        ]
      },
      
    ]
  },
   // 管理员路由（需要管理员权限）
   {
    path: '/admin',
    component: AdminLayoutVue,
    meta: { requiresAuth: true, requiresAdmin: true },
    redirect: '/admin/dashboard',
    children: [
      { path: '/admin/dashboard',name:'管理员端仪表板', component: AdminDashboardVue },
      { path: '/admin/users',name:'管理员端用户列表', component: AdminUsersVue },
      { path: '/admin/users/:id',name:'管理员端用户详情', component: AdminUserDetailVue, props: true },
      { path: '/admin/posts',name:'管理员端帖子列表', component: AdminPostsVue },
      { path: '/admin/posts/:id',name:'管理员端普通帖子详情', component: AdminPostsDetailVue, props: true },
      { path: '/admin/posts/woekdetail/:id',name:'管理员端实习/兼职帖子详情', component: AdminPostsWoekDetailVue, props: true },
      { path: '/admin/posts/categories',name:'管理员端帖子版块管理', component: AdminPostsCategoriesVue },
      { path: '/admin/posts/itemTypes',name:'管理员端帖子分类管理', component: AdminPostsItemTypeVue },
      { path: '/admin/posts/comments',name:'管理员端帖子评论管理', component: AdminPostsCommentsVue },
    ]
  },

  // 404 页面处理
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

//创建路由实例
const router = createRouter({
    history: createWebHistory(), 
    routes:routes //路由关系
});

// 路由守卫逻辑
//to - 待访问页面 from - 当前页面 next - 放行函数
router.beforeEach((to, from, next) => {
  console.log('路由跳转:', to.path)
  // console.log('token:', localStorage.getItem('token'))
  // console.log('userInfo:', localStorage.getItem('userInfo'))

  const token = localStorage.getItem('token')
  const userInfoStr = localStorage.getItem('userInfo')
  //从 localStorage 获取 token 和用户信息字符串
  const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {}
  
  const isAuthenticated = !!token//判断用户是否已登录
  const isAdmin = userInfo.role === 'admin' //判断用户是否是管理员

  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next({ name: 'login' })
  } else if (to.matched.some(record => record.meta.requiresAdmin) && (!isAuthenticated || !isAdmin)) {
    next({ path: '/' })
  // } else if (isAuthenticated && (to.name === 'login' || to.name === 'register')) {
  //   // 已登录用户访问登录/注册页，根据角色跳转
  //   if (isAdmin) {
  //     next({ name: 'admin-dashboard' })
  //   } else {
  //     next({ name: '首页' })
  //   }
  } else {
    next()
  }
})
export default router